"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能
Case Name   : 升主过程中，原主故障
Create At   : 2023/04/18
Owner       : opentestcase043
Description :
        1.查询集群状态
        2.进行switchover降备操作
        3.进行switchover升主操作时kill掉原主节点
        4.查看集群状态
        5.进行switchover升主操作时hang住原主节点
        6.查看数据库的状态
        7.解挂原始主机数据库进程
        8.查看集群状态
        9.清理环境
Expect      :
        1.集群状态正常
        2.成功
        3.成功
        4.数据库状态不可用（重启成功）
        5.成功
        6.解挂成功
        7.解挂成功
        8.状态正常
        9.清理环境成功
History     :
"""

import os
import unittest
import time

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from yat.test import Node

LOG = Logger()
Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorage(unittest.TestCase):

    def setUp(self):
        LOG.info('-----this is setup-----')
        LOG.info(f'-----{os.path.basename(__file__)} start-----')
        self.con = Constant()
        self.com = Common()
        self.pri_node = Node('PrimaryDbUser')

    def test_share_storage(self):
        text = '-----step1:查询集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step2:进行switchover降备操作; expect:成功-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('switchover', '-A')
        self.assertIn(self.con.cm_switchover_A_success_msg,
                      status, '执行失败:' + text)

        text = '-----step3:进行switchover升主操作时kill掉原主节点; '\
               'expect:成功-----'
        LOG.info(text)
        thread_1 = ComThread(Primary_SH.exec_cm_ctl, args=('switchover', '-a',))
        thread_1.setDaemon(True)
        thread_1.start()
        pri_pid = self.com.get_pid(self.pri_node, 'bin/gaussdb')
        self.assertNotEqual('', pri_pid, '执行失败:' + text)
        cmd = f'kill -9 {pri_pid}'
        thread_2 = ComThread(self.com.get_sh_result, args=(self.pri_node, cmd,))
        thread_2.setDaemon(True)
        thread_2.start()
        thread_1.join()
        msg_result1 = thread_1.get_result()
        LOG.info(msg_result1)
        self.assertTrue(self.con.cm_switchover_timeout_msg in msg_result1 or
                        self.con.cm_switchover_success_msg in msg_result1,
                        '执行失败:' + text)
        thread_2.join()
        msg_result2 = thread_2.get_result()
        LOG.info(msg_result2)
        self.assertEqual('', msg_result2, '执行失败:' + text)

        text = '-----step4:查看集群状态; expect:重启成功-----'
        LOG.info(text)
        status1 = Primary_SH.exec_cm_ctl('stop')
        LOG.info(status1)
        self.assertIn(self.con.cm_stop_success_msg, status1,
                      '执行失败:' + text)
        status2 = Primary_SH.exec_cm_ctl('start')
        LOG.info(status2)
        self.assertIn(self.con.cm_start_success_msg, status2,
                      '执行失败:' + text)
        status3 = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status3)
        self.assertIn(self.con.cm_switchover_success_msg, status3,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)

        text = '-----step5:进行switchover升主操作时hang住原主节点; '\
               'expect:成功-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('switchover', '-A')
        self.assertIn(self.con.cm_switchover_A_success_msg,
                      status, '执行失败:' + text)
        thread_1 = ComThread(Primary_SH.exec_cm_ctl, args=('switchover', '-a',))
        thread_1.setDaemon(True)
        thread_1.start()
        pri_pid = self.com.get_pid(self.pri_node, 'bin/gaussdb')
        self.assertNotEqual('', pri_pid, '执行失败:' + text)
        cmd = f'kill -19 {pri_pid}'
        LOG.info(cmd)
        thread_2 = ComThread(self.com.get_sh_result, args=(self.pri_node, cmd,))
        thread_2.setDaemon(True)
        thread_2.start()
        thread_1.join()
        msg_result1 = thread_1.get_result()
        LOG.info(msg_result1)
        self.assertIn(self.con.cm_switchover_timeout_msg,
                      msg_result1, '执行失败:' + text)
        thread_2.join()
        msg_result2 = thread_2.get_result()
        LOG.info(msg_result2)
        self.assertEqual('', msg_result2, '执行失败:' + text)

        text = '-----step6:查看集群状态; expect:集群状态异常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        self.assertNotIn('P Primary Normal', status, '执行失败:' + text)

        text = '-----step7:解挂数据库进程; expect:解挂成功-----'
        LOG.info(text)
        cmd = f"kill -18 {pri_pid}"
        LOG.info(cmd)
        status = self.pri_node.sh(cmd).result()
        LOG.info(status)
        self.assertEqual('', status, '执行失败:' + text)

        text = '-----step8:查看集群状态; expect:集群状态不可用-----'
        LOG.info(text)
        time.sleep(30)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)

    def tearDown(self):
        text = '-----this is tearDown-----'
        LOG.info(text)
        text = '-----step9:清理环境; expect:清理环境成功-----'
        LOG.info(text)
        pri_pid = self.com.get_pid(self.pri_node, 'bin/gaussdb')
        self.assertNotEqual('', pri_pid, '执行失败:' + text)
        cmd = f'kill -18 {pri_pid}'
        status1 = self.pri_node.sh(cmd).result()
        status2 = Primary_SH.exec_cm_ctl('stop')
        status3 = Primary_SH.exec_cm_ctl('start')
        status4 = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status1)
        LOG.info(status2)
        LOG.info(status3)
        LOG.info(status4)
        self.assertEqual('', status1, '执行失败:' + text)
        self.assertIn(self.con.cm_stop_success_msg, status2,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_start_success_msg, status3,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_switchover_success_msg, status4,
                      '执行失败:' + text)
        LOG.info(f'-----{os.path.basename(__file__)} end-----')
